package com.shuwen.gcdj.common.util.file;

import com.alibaba.excel.EasyExcel;
import com.shuwen.gcdj.entity.TestBean;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/***
 ** Created by ljf
 ** Date:2023/3/14
 */
public class ExcelFileUtil {

    public static void exportEasyExcel(List<TestBean> list,HttpServletResponse response){
        String fileName = null;
        try {
            fileName = URLEncoder.encode("test", "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/force-download");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Content-Type","application/octet-stream;charset=utf-8");
            /**导出结果流*/
            //遍历列表，求各数据汇总
            TestBean capacityPo=new TestBean();
            capacityPo.setExport("汇总");
            capacityPo.setTime("汇总");
            capacityPo.setDirection("汇总");
            //模拟数据-勿动
            capacityPo.setData1(list.stream().filter(Po-> Po.getData1()!=null).mapToDouble(TestBean::getData1).sum());
            capacityPo.setData2(list.stream().filter(Po-> Po.getData2()!=null).mapToDouble(TestBean::getData2).sum());
            capacityPo.setData3(list.stream().filter(Po-> Po.getData3()!=null).mapToDouble(TestBean::getData3).sum());
            capacityPo.setData4(list.stream().filter(Po-> Po.getData4()!=null).mapToDouble(TestBean::getData4).sum());
            capacityPo.setData5(list.stream().filter(Po-> Po.getData5()!=null).mapToDouble(TestBean::getData5).sum());
            capacityPo.setData6(list.stream().filter(Po-> Po.getData6()!=null).mapToDouble(TestBean::getData6).sum());
            list.add(capacityPo);

            ArrayList<CellLineRange> cellLineRanges = new ArrayList<>();
            //设置第几列开始合并
            int[] mergeColumnIndex = {0,1,2,3};
            //设置第几行开始合并
            int mergeRowIndex = 3;

            cellLineRanges.add(new CellLineRange(5,6));
            EasyExcel.write(response.getOutputStream())
                    //设置行合并单元格
                    .registerWriteHandler(new ExcelFillCellRowMergeStrategyUtil(mergeRowIndex,mergeColumnIndex))
                    //设置行合并单元格
                    .registerWriteHandler(new ExcelFillCellColMergeStrategyUtil(cellLineRanges,5))
                    .head(TestBean.class)
                    .sheet("sheet1")
                    .doWrite(list);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

